import json
from pathlib import Path
import config

def load_json(path:str):
    with Path(path).open(encoding='utf-8') as f:
        return json.load(f)
    

def tasks_gen(flows):
    d   = config.MAX_TASK_DELAY
    jit = config.MAX_TASK_JIT
    p   = config.PROCESSING_TASK_TIME     
    transactions_map = {}
    tasks = {}
    latency_bound = [0] * len(flows)
    t_idx = 0
    for f_idx,f in enumerate(flows):
        transactions_map[f_idx] = f['fid']
        latency_bound[f_idx]=f['latency']
        release_time = f['release']
        T = f['period']

        for idx,fix in enumerate(f['route']):
            if idx == len(f['route'])-1:
                continue
            tasks[t_idx] = {'r':release_time,'d':d,'T':T,'jit':jit,'p':p,'fix':fix,'transaction':f_idx}
            if idx == 0:
                tasks[t_idx]['pred'] = []
                if len(f['route']) > 2:
                    tasks[t_idx]['succ'] = [t_idx+1]
                else:
                    tasks[t_idx]['succ'] = []
                tasks[t_idx]['next'] = [f['route'][idx+1]]
            elif idx == len(f['route'])-2 and idx!=0:
                tasks[t_idx]['pred'] = [t_idx-1]
                tasks[t_idx]['succ'] = []
                tasks[t_idx]['next'] = [f['route'][idx+1]]
            else:
                tasks[t_idx]['pred'] = [t_idx-1]
                tasks[t_idx]['succ'] = [t_idx+1]
                tasks[t_idx]['next'] = [f['route'][idx+1]]
            t_idx = t_idx + 1
    return tasks,transactions_map,latency_bound



def json_parse(path:str):
    data = load_json(path)
    json.dumps(data,indent=2,ensure_ascii=False)
    return tasks_gen(data["flows"])


if __name__ == "__main__":
    data = load_json("./inputs/example1.json")
    json.dumps(data,indent=2,ensure_ascii=False)
    
    # 简单访问示例
    # print("\n任务列表：")
    # for t in data["flows"]:
    #     print(t)
    #     print(f"  {t['fid']}  路由={t['route']}  周期={t['period']}")
        
        
    # tasks,transcation_map,latency_bound = tasks_gen(data["flows"])
    tasks,transcation_map,latency_bound = json_parse("./inputs/example1.json")
    print(f"transcation_map:{transcation_map}")
    print(f"latency_bound:{latency_bound}")
    for idx,t in tasks.items():
        print(idx,t)
    
